<?php
/**
 * Created by PhpStorm.
 * User: tom_xia
 * Date: 2018/6/7
 * Time: 14:38
 * 原始视频混音
 */
require_once dirname(__DIR__)."/common.php";
use app\cls\tom\Lock;
use app\cls\tom\FFmpeg;
use app\lib\db\DbException;
use app\cls\tom\SysResource;
use app\cls\tom\Process;
use app\cls\tom\Tools;

$process = new Process(__FILE__);
$process->setProcessNum(1);
$process->initProcess();
$process->isTryError = false;
$redis = SysResource::getRedis();
$db =  SysResource::getDB(true);
$ffmpeg = new FFmpeg();
/*===============
 *初始化模型
 ================*/
$videoModel = new \app\model\Video($db);
$cosUploadConfig = \app\cls\tom\Config::load("cos_upload");
$lock = new Lock("ori_material_audio_video_mix");
while(true){
    try{
        $readyList = $videoModel->getReadyHandleVideoMusic(10);
        print_r($readyList);
        foreach($readyList as &$row){
//            var_dump($lock->unLock($row["id"]));continue;
            $lockStatus = $lock->tryLock($row["id"]);
            if($lockStatus){
                $oriVideoUrl = $row["ori_video_url"];
                $noAudioVideo = $row["no_audio_video_url"];
                //1.裁剪音频
                $totalStatus = [];
                if(empty($row["cut_music_url"])){
                    $oriMusicUrl = $row["ori_music_url"];
                    $videoTime = $row["video_time"];
                    if(empty($videoTime)){
                        $videoTime = $ffmpeg->getVideoLen($oriVideoUrl);
                    }
                    $audioTime = $row["audio_length"];
                    if(empty($audioTime)){
                        $audioTime = $ffmpeg->getVideoLen($oriMusicUrl);
                    }
                    if($audioTime>$videoTime){
                        $tempPath = CDN_PATH."/cut_audio/";
                        $cutAudios = $ffmpeg->cutVideo($oriMusicUrl,$tempPath,[["start"=>"00:00:00","duration"=>$ffmpeg->formatFFmpegTime($videoTime)]]);
                        if(empty($cutAudios)){
                            Tools::writeLog(["msg"=>"原始素材音视频混音失败","detail"=>["media_id"=>$row["id"],"msg"=>$ffmpeg->getLastError()],"ori_mix"]);
                            $db->update("video",["transcode_status"=>2,"transcode_msg"=>$ffmpeg->getLastError(),"transcode_count"=>"!transcode_count+1"],["id"=>$row["id"]]);
                            $lock->unLock($row["id"]);
                            continue;
                        }
                        $musicUrl = str_replace(CDN_PATH,CDN_HOST,$cutAudios[0]);
                    }else{
                        $musicUrl = $oriMusicUrl;
                    }
                    $audioPath = str_replace(CDN_HOST,CDN_PATH,$musicUrl);
                    $db->update("video",["cut_music_url"=>$musicUrl],["id"=>$row["id"]]);
                    $totalStatus[] = 1;
                }else{
                    $audioPath = str_replace(CDN_HOST,CDN_PATH,$row["cut_music_url"]);
                    $totalStatus[] = 1;
                }
                //2.有音频视频转码
                if(empty($row["transcode_video_url"])){
                    $outPutPath = CDN_PATH."/transCodeV1/".pathinfo($oriVideoUrl,PATHINFO_BASENAME);
                    $oriVideoPath = str_replace(CDN_HOST,CDN_PATH,$oriVideoUrl);
                    $re = $ffmpeg->transCode($oriVideoPath,$outPutPath);
                    if(!$re){
                        Tools::writeLog(["msg"=>"有音频视频转码失败","detail"=>["media_id"=>$row["id"],"msg"=>$ffmpeg->getLastError()],"ori_mix"]);
                        $db->update("video",["transcode_status"=>2,"transcode_msg"=>$ffmpeg->getLastError(),"transcode_count"=>"!transcode_count+1"],["id"=>$row["id"]]);
                        $lock->unLock($row["id"]);
                        continue;
                    }
                    $db->reconnect();
                    $db->update("video",["transcode_video_url"=>str_replace(CDN_PATH,CDN_HOST,$outPutPath)],["id"=>$row["id"]]);
                    $totalStatus[] = 1;
                }else{
                    $totalStatus[] = 1;
                }
                if(empty($row["transcode_no_audio_video_url"])){
                    //3。无音频视频转码
                    $noAudioOutPutPath = CDN_PATH."/transCodeV2/".pathinfo($noAudioVideo,PATHINFO_BASENAME);
                    $noAudioOriVideoPath = str_replace(CDN_HOST,CDN_PATH,$noAudioVideo);
                    $re = $ffmpeg->transCode($noAudioOriVideoPath,$noAudioOutPutPath);
                    if(!$re){
                        Tools::writeLog(["msg"=>"无音频视频转码失败","detail"=>["media_id"=>$row["id"],"msg"=>$ffmpeg->getLastError()],"ori_mix"]);
                        $db->update("video",["transcode_status"=>2,"transcode_msg"=>$ffmpeg->getLastError(),"transcode_count"=>"!transcode_count+1"],["id"=>$row["id"]]);
                        $lock->unLock($row["id"]);
                        continue;
                    }
                    $db->reconnect();
                    $db->update("video",["transcode_no_audio_video_url"=>str_replace(CDN_PATH,CDN_HOST,$noAudioOutPutPath)],["id"=>$row["id"]]);
                    $totalStatus[] = 1;
                }else{
                    $totalStatus[] = 1;
                }
                if(count($totalStatus) == 3){
                    $db->update("video",["transcode_status"=>1,"transcode_msg"=>"转码成功","transcode_count"=>"!transcode_count+1"],["id"=>$row["id"]]);
                }
                $lock->unLock($row["id"]);
            }
        }
    }catch (DBException $e){
        echo $e->getMessage();
//        $process->restartProcess();
    }catch (RedisException $e){

    }catch (Exception $e){
        if(!empty($row)){
            $db->update("video",["transcode_status"=>2,"transcode_msg"=>$e->getMessage(),"transcode_count"=>"!transcode_count+1"],["id"=>$row["id"]]);
            $lock->unLock($row["id"]);
        }
        Tools::writeLog(["msg"=>"音视频混音失败","detail"=>["msg"=>$e->getMessage(),"id"=>$id],"mix"]);
    }
    sleep(2);
    $process->checkProcessTime(true);
    $db->reconnect();
}